package cn.sgy.infrastructure.web.initialize.config;

import cn.sgy.infrastructure.web.initialize.business.InitializeDispatcherServletController;
import cn.sgy.infrastructure.web.initialize.business.InitializeDispatcherServletHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author sgy
 * @description web初始化自动配置类
 * @date 2023-05-28
 */
@ConditionalOnProperty(prefix = "infrastructure.web.init", value = {"enable"}, havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
public class WenInitAutoConfiguration {
    public final static String INITIALIZE_PATH = "/initialize/dispatcher-servlet";

    /**
     * 一个Controller，提供一个接口，用作在初始化的时候访问，来进行预热
     *
     * @return
     */
    @Bean
    public InitializeDispatcherServletController initialzeDispatcherServletController() {
        return new InitializeDispatcherServletController();
    }

    /**
     * 自定义RestTemplate
     *
     * @param factory
     * @return
     */
    @ConditionalOnMissingBean
    @Bean
    public RestTemplate simpleRestTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    /**
     * 自定义ClientHttpRequestFactory来设置RestTemplate的
     *
     * @return
     */
    @ConditionalOnMissingBean
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(5000);
        return factory;
    }

    /**
     * 实现了CommandLineRunner接口，能在SpringBoot项目启动后做一些事情
     * 这里面做的事情就是使用RestTemplate访问InitializeDispatcherServletController提供的接口来进行预热
     *
     * @param restTemplate
     * @param configurableEnvironment
     * @return
     */
    @Bean
    public InitializeDispatcherServletHandler initializeDispatcherServletHandler(RestTemplate restTemplate, ConfigurableEnvironment configurableEnvironment) {
        return new InitializeDispatcherServletHandler(restTemplate, configurableEnvironment);
    }
}
